#include "ToolBar.h"
#include "ToolBase.h"
#include "ToolManager.h"
#include "ToolButton.h"

ToolBar::ToolBar(const QString &title, QMainWindow *parent, int nbColumn) :
    QToolBar(title, parent), ToolManager(this), m_nbColumn(nbColumn)
{
    m_mapper = new QSignalMapper(this);
    connect(m_mapper, SIGNAL(mapped(QWidget *)), SLOT(buttonClicked(QWidget*)));
}

ToolBar::~ToolBar()
{
}

void
ToolBar::addTool(ToolBase *tool)
{
    if(! tool->iconPath().isEmpty() && m_toolMap.find(tool) == m_toolMap.end())
    {
        ToolButtonMap::iterator it = m_toolMap.end();
        QString group = tool->group();
        if(! group.isEmpty())
        {
            for(it = m_toolMap.begin(); it != m_toolMap.end(); ++it)
            {
                if(it->first->group() == group)
                    break;
            }
        }

        ToolButton *button = nullptr;
        bool newButton = false;
        if(it != m_toolMap.end())
        {
            button = it->second;
        }
        else
        {
            button = new ToolButton(this, tool);
            newButton = true;
        }

        if (newButton) {
            button->setAutoExclusive(true);
            connect(button, SIGNAL(clicked()), m_mapper, SLOT(map()));
            m_mapper->setMapping(button, button);
            button->setChecked(true);
            addWidget(button);
        }
        m_toolMap[tool] = button;
    }
    ToolManager::addTool(tool);
}

ToolButton *
ToolBar::getButton(ToolBase *tool) const
{
    ToolButtonMap::const_iterator it = m_toolMap.find(tool);
    if(it != m_toolMap.end())
        return it->second;
    return nullptr;
}

void
ToolBar::selectTool(ToolBase *tool)
{
    ToolManager::selectTool(tool);
    QAbstractButton *button = getButton(tool);
    if (button != nullptr) {
        button->setChecked(true);
    }
}

void
ToolBar::removeTool(ToolBase *tool)
{
    ToolButton *button = getButton(tool);
    if (button != nullptr) {
        m_mapper->removeMappings(button);
        button->disconnect(m_mapper, SLOT(map()));
        delete button;
    }
    ToolManager::removeTool(tool);
}

void
ToolBar::buttonClicked(QWidget *button)
{
    ToolButton *btn = dynamic_cast<ToolButton *>(button);
    if(btn != nullptr)
        ToolManager::selectTool(btn->tool());
}
